package com.example.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.config.R;
import com.example.dao.DishDao;
import com.example.dao.SetmealDao;
import com.example.entity.*;
import com.example.service.CategoryService;
import com.example.service.DishFloverService;
import com.example.service.DishService;
import org.apache.ibatis.annotations.Delete;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFloverService dishFlavorService;


    @RequestMapping("/page")
    public R page(Integer page, Integer pageSize, String name){
        IPage<Category> pageInfo=new Page<>(page,pageSize);
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();

        if (name!=null){
            queryWrapper.like(Category::getName, name);
        }
        //queryWrapper.orderByDesc(Employee::getUpdateTime);
        //loginService.page(pageInfo,queryWrapper);
        IPage<Category> iPage = categoryService.page(pageInfo, queryWrapper);
        return R.success(iPage);
    }

    @PostMapping
    public R addCategory(@RequestBody Category category, HttpSession session){
        Long id=(Long)session.getAttribute("employee");
        category.setCreateUser(id);
        category.setUpdateUser(id);
//        if (category.getName()!=null){
//           return R.error("名字以重复");
//        }
        categoryService.add(category);
        return R.success("成功");
    }

    @DeleteMapping
    public R del(Long id){
        categoryService.del(id);
        return R.success("删除成功");
    }



    @GetMapping("/exportExcel")
    public void exportExcel(HttpServletResponse response) throws IOException {
        //1. 读取模板的输入流
        InputStream inputStream = this.getClass().getResourceAsStream("/excel/cateory.xlsx");

        //2. 使用模块输入流创建工作簿
        Workbook workbook = new XSSFWorkbook(inputStream);

        //3. 得到工作单，得到第一行，并且提取样式存储到集合中
        Sheet sheet = workbook.getSheetAt(0);
        Row row = sheet.getRow(1);
        //定义一个集合存储单元格的样式
        List<CellStyle> cellStyleList = new ArrayList<>();
        for (int i = 1; i <=5 ; i++) {
            //得到每一个单元格的样式
            CellStyle cellStyle = row.getCell(i).getCellStyle();
            //存储到集合中
            cellStyleList.add(cellStyle);
        }
        //4. 得到所有的类别集合
        List<Category> categoryList = categoryService.findAll();

        //5. 遍历类别集合，设置样式与数据
        for (int i = 0; i < categoryList.size(); i++) {
            //得到一个类别，每一个类别就是一行数据
            Category category = categoryList.get(i);
            //创建行
            row = sheet.createRow(i+1);

            //创建单元格并且设置单元格
            //类别类型
            Cell cell = row.createCell(1);
            cell.setCellStyle(cellStyleList.get(0));
            cell.setCellValue(category.getType());

            //类别名称
            cell = row.createCell(2);
            cell.setCellStyle(cellStyleList.get(1));
            cell.setCellValue(category.getName());

            //排序
            cell = row.createCell(3);
            cell.setCellStyle(cellStyleList.get(2));
            cell.setCellValue(category.getSort());

            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

            //创建时间
            cell = row.createCell(4);
            cell.setCellStyle(cellStyleList.get(3));
            cell.setCellValue(dateTimeFormatter.format(category.getCreateTime()));


            //修改时间
            cell = row.createCell(5);
            cell.setCellStyle(cellStyleList.get(4));
            cell.setCellValue(dateTimeFormatter.format(category.getUpdateTime()));
        }

        //6. 输出工作簿即可,通知浏览器当前是以文件下载的形式去处理内容。
        response.setHeader("content-disposition","attachment;filename=category.xlsx");
        workbook.write(response.getOutputStream());
    }

    @PutMapping
    public R update(@RequestBody Category category,HttpSession session){
        Long id =(Long) session.getAttribute("employee");
        category.setUpdateUser(id);
        categoryService.updateCategory(category);
        return  R.success("修改成功");
    }


//    @GetMapping("/list")
//    public R list(Dish dish) {
//        //检查参数
//        if (dish == null) {
//            return null;
//        }
//        //构件查询条件
//        LambdaQueryWrapper<Dish> wraper = new LambdaQueryWrapper<>();
//        //当传入的id不为空,且比较数据库的菜品分类id=传入的id
//        wraper.eq(dish.getCategoryId() != null,
//                Dish::getCategoryId, dish.getCategoryId());
//        //添加条件,查询状态为1(起售)的菜品
//        wraper.eq(Dish::getStatus, 1);
//        //根据条件排序
//        wraper.orderByAsc(Dish::getSort).orderByAsc(Dish::getUpdateTime);
//        List<Dish> list = dishService.list(wraper);
//        List<DishDto> dishDtoList = list.stream().map((s) -> {
//            //创建一个dishDto对象
//            DishDto dishDto = new DishDto();
//            //把dish集合里面的dish对象封住到dto
//            BeanUtils.copyProperties(s, dishDto);
//            //分类的id
//            Long categoryId = s.getCategoryId();
//            //根据分类的id查询分类对象
//            Category category = categoryService.getById(categoryId);
//            //当对象不为null,把分类对象的名字设置到Dto
//            if (category != null) {
//                String name = category.getName();
//                dishDto.setCategoryName(name);
//            }
//            //当前菜品的id
//            Long dishId = s.getId();
//            LambdaQueryWrapper<DishFlavor> dishWrapper = new LambdaQueryWrapper<>();
//            //设置口味信息,id
//            dishWrapper.eq(DishFlavor::getDishId, dishId);
//            List<DishFlavor> list1 = dishFlavorService.list(dishWrapper);
//            dishDto.setFlavors(list1);
//            return dishDto;
//        }).collect(Collectors.toList());
//
//        return R.success(dishDtoList);
//    }


//


    @GetMapping("/list")
    public R<List<Category>> list(Category category){
        //条件构造器
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        //添加条件
        queryWrapper.eq(category.getType() != null,Category::getType,category.getType());
        //添加排序条件
        queryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);

        List<Category> list = categoryService.list(queryWrapper);
        return R.success(list);
    }
}
